<?php
/**
 * Created by PhpStorm.
 * User: Merdan
 * Date: 2017/3/28
 * Time: 2:59
 */

namespace App\Services;

use App\Exceptions\NotExistException;
use App\Models\Product as ProductModel;

class Product extends BaseService
{
    /**
     * 获取物料列表
     *
     * @param $limit
     * @param array $filter
     * @return mixed
     */
    public function getList($limit, $filter = [])
    {
        $products = ProductModel::select()->with('category');
        if (isset($filter['name'])) {
            $name = $filter['name'];
            $products->where('name', 'like', "%$name%");
        }
        if (isset($filter['for']) && $filter['for'] == 'sku') {
            $canteen_id = auth()->user()->canteen->id;
            $products->whereDoesntHave('sku', function ($query) use ($canteen_id) {
                $query->where('canteen_id', $canteen_id);
            });
        }
        return $products->paginate($limit);
    }

    /**
     * 获取单个物料信息
     *
     * @param $id
     * @return mixed
     * @throws NotExistException
     */
    public function show($id)
    {
        $product = ProductModel::with('category')->find($id);
        if (!$product) throw new NotExistException('物料不存在');
        return $product;
    }

    /**
     * 创建物料
     *
     * @param $data
     * @return ProductModel
     */
    public function create($data)
    {
        return ProductModel::create($data);
    }

    /**
     * 更新物料
     *
     * @param $id
     * @param $data
     * @return mixed
     * @throws NotExistException
     */
    public function update($id, $data)
    {
        $product = ProductModel::find($id);
        $data = array_filter($data, function ($item) {
            return $item != null;
        });
        if (!$product) throw new NotExistException('物料不存在');
        $product->update($data);

        return $product;
    }

    /**
     * 获取所有分类
     *
     * @return mixed
     */
    public function cateogries()
    {
        return \App\Models\Category::select()->withCount('product')->get();
    }

}